package com.itheima.reggie.controller;
import com.itheima.reggie.Utils.EmailUtils;
import com.itheima.reggie.Utils.ValidateCodeUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author 669
 * @CreateDate 2023/2/28 23:12
 * @Version 1.0
 */

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        /**
         *  //获取手机号
         *         String phone = user.getPhone();
         *         if(StringUtils.isNotEmpty(phone)){
         *             //生成随机的4位验证码
         *             String code = ValidateCodeUtils.generateValidateCode(4).toString();
         *             log.info("code={}",code);
         *
         *             //调用阿里云提供的短信服务API完成发送短信
         *             //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
         *
         *             //调用工具类进行邮箱验证
         *             // EmailUtils.sendEmail();
         *
         *             //需要将生成的验证码保存到Session
         *             session.setAttribute(phone,code);
         *             return R.success("手机验证码短信发送成功");
         *         }
         *         return R.error("短信发送失败");
         */

        if (userService.sendMsg(user, session)) {
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    /**
     * 用户登陆
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        User user = userService.login(map, session);
        return R.success(user);
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        log.info("用户退出成功");
        return R.success("退出成功");
    }
}